import { instructAttachmentPreview } from '@/services/api/api-instruct-attachment';
import { selectRecord } from '@/services/api/api-instruct-record';
import { CheckOutlined, CopyOutlined, DownloadOutlined } from '@ant-design/icons';
import { DrawerForm, ProFormInstance } from '@ant-design/pro-form';
import { WaterMark } from '@ant-design/pro-layout';
import { useAccess, useModel } from '@umijs/max';
import {
  Alert,
  Button,
  Descriptions,
  Divider,
  Flex,
  Image,
  message,
  Result,
  Space,
  Spin,
  Tag,
  Typography,
  Upload,
  UploadFile,
} from 'antd';
import { useEffect, useRef, useState } from 'react';
import AddReceipt from '../receipt/AddReceipt';
import ListReceipt from '../receipt/ListReceipt';
import ReceiptAssign from '../receipt/ReceiptAssign';
import EditRecord from './EditRecord';
import { ManageRecord } from './ManageRecord';
interface DetailsRecordProps {
  item: InstructRecordData.PageVo;
  onClose: () => void;
  instructId: string;
}

const DetailsRecord: React.FC<DetailsRecordProps> = ({ item, onClose, instructId }) => {
  const { initialState } = useModel('@@initialState');

  const ref = useRef<ProFormInstance>();

  const access = useAccess();

  const [record, setRecordState] = useState<InstructRecordData.ResultDetails>();
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewData, setPreviewData] = useState<{
    id: string;
    name: string;
    mimeType: string;
    url?: string;
  }>();
  const [previewOnlineUrl, setPreviewOnlineUrl] = useState<string>();
  const [previewLoading, setPreviewLoading] = useState(true);
  const [drawerFormVisible, setDrawerFormVisible] = useState(false);

  const [reload, setReloadState] = useState(false);

  const getWindowSize = () => ({
    innerHeight: window.innerHeight,
    innerWidth: window.innerWidth,
  });
  const [windowSize, setWindowSize] = useState(getWindowSize());
  const handleResize = () => {
    setWindowSize(getWindowSize());
  };
  useEffect(() => {
    // 监听
    window.addEventListener('resize', handleResize);
    // 销毁
    return () => window.removeEventListener('resize', handleResize);
  });
  useEffect(() => {
    if (instructId === item.id) {
      if (instructId !== undefined) {
        setDrawerFormVisible(true);
      }
    }
  }, []);

  const iframeRef = useRef(null);

  const handleLoad = () => {
    console.log('加载完成');
    setPreviewLoading(false);
  };
  useEffect(() => {
    const iframe = iframeRef.current;
    iframe?.addEventListener('load', handleLoad);
    return () => {
      iframe?.removeEventListener('load', handleLoad);
    };
  }, [previewOnlineUrl]);

  /**
   * 获取 详情
   * @param key
   */
  const getSubmitDetails = async () => {
    try {
      const response = await selectRecord({ id: item.id });
      if (response.code === 0) {
        setRecordState(response.data);
      }
    } catch (error) { }
  };

  return (
    <DrawerForm
      open={drawerFormVisible}
      key={`drawer_form_detail_record_${item.id}`}
      title={
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          <div>
            {record?.run === 2 ? <Tag color="red">已结束</Tag> : ''}
            {record?.isAlreadyDestroyed === 1 ? <Tag color="red">已焚毁</Tag> : ''}
            <span>{record?.name}</span>
          </div>
          <div>
            {access.宣传指令x配置x管理员 && record?.run === 1 && (
              <EditRecord
                key="edit_role"
                recored={item}
                onRefurbish={() => {
                  // actionRef.current?.reload();
                  getSubmitDetails();
                }}
              />
            )}
            {access.宣传指令x配置x指令审批 && record?.examine === 0 && (
              <ManageRecord
                title={record?.name}
                id={record?.id}
                type="botton"
                onRefurbish={() => {
                  getSubmitDetails();
                }}
              />
            )}
          </div>
        </div>
      }
      trigger={
        <Typography.Text ellipsis={true} style={{ width: 200 }}>
          <a key="a_detail_record">{item.name} </a>
        </Typography.Text>
      }
      autoFocusFirstInput
      drawerProps={{
        size: 'large',
        forceRender: true,
        destroyOnClose: true,
        width: '1000px',
      }}
      submitter={{
        render: (props, defaultDoms) => {
          return [
            // ...defaultDoms,
            access.宣传指令x配置x接收者
            && record?.run === 1 && record?.completeType == 3 && (
              <AddReceipt
                onSave={() => {
                  setReloadState(!reload);
                  getSubmitDetails();
                }}
                recordId={record?.id}
              />
            ),
          ];
        },
      }}
      onOpenChange={(visible) => {
        if (visible) {
          window.parent.postMessage({ message: '阅读情况改变' }, '*');
          setReloadState(!reload);
          getSubmitDetails();
        } else {
          onClose();
        }
        setDrawerFormVisible(visible);
      }}
    >
      <Spin spinning={record ? false : true}>
        <WaterMark content={`宣传指令 - ${initialState?.currentUser?.name}`}>
          <>
            {record && (
              <>
                <div>
                  <Space
                    wrap
                    style={{
                      marginBottom: 16,
                    }}
                  >
                    {access.宣传指令x配置x管理员 && (
                      <Tag
                        color={
                          record.examine === 0
                            ? '#2db7f5'
                            : record.examine === 2
                              ? '#f50'
                              : '#87D068'
                        }
                      >
                        {record.examine === 0 ? '待审批' : record.examine === 2 ? '退回' : '通过'}
                      </Tag>
                    )}
                    <Tag
                      color={
                        record.grade === 1 ? '#f50' : record.grade === 2 ? '#ffd591' : '#2db7f5'
                      }
                    >
                      {record.grade === 1 ? '重大' : record.grade === 2 ? '重要' : '一般'}
                    </Tag>
                    <Tag color={record.type === 1 ? '#f50' : '#ffd591'}>
                      {record.type === 1 ? '中宣' : '市宣'}
                    </Tag>
                  </Space>
                </div>

                {/* {access.宣传指令x配置x管理员 &&
                        record.isHasView === 1 &&
                        record.isView === 0 ? (
                          <Tag color={'#F9CF59'} key="tag_is_has_view">
                            需要阅读
                          </Tag>
                        ) : (
                          <></>
                        )} */}

                {access.宣传指令x配置x接收者 && (
                  <Descriptions>
                    <Descriptions.Item label="操作情况">
                      <Space wrap>
                        <Tag
                          color={record.isView === 0 ? '#F9CF59' : '#1AA15F'}
                          key="recordExamineType"
                        >
                          {record.isView === 0 ? '未阅读' : '已阅读'}
                        </Tag>
                        {record?.isComplete === 1 ? (
                          <Tag color={'success'}>{'已完成'}</Tag>
                        ) : (
                          <Tag color={record?.completeType === 1 ? 'success' : 'error'}>
                            {record?.completeType === 1 ? '无需回执' : '需要回执'}
                          </Tag>
                        )}

                        {record?.isCompleteWithinDeadlineTimeOwn === 1 ? (
                          <Tag color={'success'}>在截止时间内自己已完成</Tag>
                        ) : (
                          <Tag color={'error'}>在截止时间内自己未完成</Tag>
                        )}
                        {record?.isCompleteWithinDeadlineTimeOrganization === 1 ? (
                          <Tag color={'success'}>在截止时间内单位已完成</Tag>
                        ) : (
                          <Tag color={'error'}>在截止时间内单位未完成</Tag>
                        )}
                      </Space>
                    </Descriptions.Item>
                  </Descriptions>
                )}
                <Descriptions>
                  <Descriptions.Item label="创建时间">{record?.createdTime}</Descriptions.Item>
                  <Descriptions.Item label="截止时间">{record?.deadlineTime}</Descriptions.Item>
                </Descriptions>
                <Descriptions>
                  <Descriptions.Item label="发布单位">
                    {record?.createdOrganizationName}
                  </Descriptions.Item>
                  <Descriptions.Item label="发布人">{record?.createdAccountName}</Descriptions.Item>
                  <Descriptions.Item label="联系方式">
                    {record?.createdAccountPhone}
                  </Descriptions.Item>
                </Descriptions>
                {access.宣传指令x配置x管理员 ? (
                  <Descriptions>
                    <Descriptions.Item label="指令要求">
                      <Tag color={record?.completeType === 1 ? 'success' : 'error'}>
                        {record?.completeType === 1 ? '无需回执' : '需要回执'}
                      </Tag>
                    </Descriptions.Item>

                    <Descriptions.Item label="">
                      <ReceiptAssign
                        id={record.id}
                        deadlineTime={record.deadlineTime}
                        receipt={'阅读情况：' + record.read}
                        type="read"
                        isRun={record.run === 1}
                      />
                    </Descriptions.Item>
                    {record.completeType === 3 && (
                      <Descriptions.Item label="">
                        <ReceiptAssign
                          id={record.id}
                          deadlineTime={record.deadlineTime}
                          receipt={'回执情况：' + record.receipt}
                          type="receipt"
                          isRun={record.run === 1}
                        />
                      </Descriptions.Item>
                    )}
                  </Descriptions>
                ) : (
                  <></>
                )}
                <Divider />
                {record?.name ? (
                  <Typography.Title
                    copyable={{
                      icon: [
                        <CopyOutlined
                          style={{
                            fontSize: '16px',
                          }}
                          key="copy-icon"
                        />,
                        <CheckOutlined
                          style={{
                            fontSize: '16px',
                          }}
                          key="copied-icon"
                        />,
                      ],
                    }}
                    level={3}
                    style={{ textAlign: 'center' }}
                  >
                    {record?.name}
                  </Typography.Title>
                ) : (
                  <Typography.Title level={3} style={{ textAlign: 'center' }}>
                    暂无标题
                  </Typography.Title>
                )}
                {record?.isAlreadyDestroyed == 1 ? (
                  <Result
                    status="error"
                    title="该条指令已被焚毁"
                    subTitle="如果想了解信息，请联系发布人"
                  />
                ) : (
                  <>
                    <Flex justify={'flex-end'} align={'center'}>
                      <Typography.Paragraph
                        copyable={{
                          icon: [
                            <Tag color="#108ee9" key="copy-icon">
                              复制全文
                            </Tag>,
                            <CheckOutlined
                              style={{
                                fontSize: '16px',
                              }}
                              key="copied-icon"
                            />,
                          ],
                          text: async () =>
                            new Promise((resolve) => {
                              var tempDivElement = document.createElement('div');
                              tempDivElement.innerHTML = record?.content;
                              resolve(tempDivElement.textContent || tempDivElement.innerText || '');
                            }),
                        }}
                      />
                    </Flex>

                    <div
                      dangerouslySetInnerHTML={{
                        __html: `${record?.content}`,
                      }}
                    />
                  </>
                )}
                {/* <SearchableContent content={record?.content}/> */}
              </>
            )}
            {record?.attachments && record?.attachments.length > 0 && (
              <>
                <Divider />
                <div
                  style={{
                    textAlign: 'right',
                  }}
                >
                  <Button
                    type="primary"
                    key="import"
                    size="small"
                    icon={<DownloadOutlined />}
                    onClick={() => {
                      record?.attachments.forEach(function (item) {
                        window.open(item.content, '_blank');
                      });
                    }}
                  >
                    全部下载
                  </Button>
                </div>

                <Upload
                  listType="picture"
                  multiple
                  fileList={record?.attachments.map((item) => {
                    return {
                      uid: item.id,
                      name: item.name,
                      url: item.content,
                      mimeType: item.mimeType,
                      status: 'done',
                    };
                  })}
                  showUploadList={{
                    downloadIcon: (
                      <div style={{ marginLeft: '-100px', padding: '17px 0', marginTop: '-15px' }}>
                        <DownloadOutlined
                          style={{
                            marginRight: '10px',
                          }}
                        />
                        点击下载
                      </div>
                    ),
                    showRemoveIcon: false,
                    showDownloadIcon: true,
                  }}
                  onPreview={async (file: UploadFile) => {
                    setPreviewData({
                      id: file.uid,
                      name: file.name,
                      mimeType: file.mimeType,
                      url: file.url,
                    });
                    setPreviewOpen(true);
                  }}
                />
                <DrawerForm
                  title={previewData?.name}
                  drawerProps={{
                    width: 900,
                    destroyOnClose: true,
                  }}
                  open={previewOpen}
                  onOpenChange={async (visible) => {
                    if (visible) {
                      if (
                        previewData?.mimeType !== null &&
                        previewData?.mimeType?.indexOf('image') > -1
                      ) {
                        //图片预览
                      } else {
                        setPreviewLoading(true);
                        const response = await instructAttachmentPreview({
                          id: previewData?.id,
                        });

                        if (response.code === 0) {
                          setPreviewOnlineUrl(response.data);
                        } else {
                          message.error('暂时无法预览');
                          setPreviewLoading(false);
                        }
                      }
                    } else {
                      setPreviewOpen(false);
                      setPreviewData(undefined);
                      setPreviewOnlineUrl(undefined);
                    }
                  }}
                  submitter={{
                    searchConfig: {
                      submitText: '下载',
                    },
                  }}
                  onFinish={async (values) => {
                    window.open(previewData?.url, '_blank');
                  }}
                >
                  <Alert
                    style={{
                      marginBottom: 20,
                    }}
                    message="部分文件系统可能暂不支持在线预览，建议下载到本地"
                    type="warning"
                    showIcon
                  />
                  {previewData?.mimeType !== null &&
                    previewData?.mimeType?.indexOf('image') > -1 ? (
                    <Image width="100%" src={previewData?.url} />
                  ) : (
                    <Spin spinning={previewLoading}>
                      <iframe
                        ref={iframeRef}
                        src={previewOnlineUrl}
                        height={windowSize.innerHeight - 220}
                        width="100%"
                        frameBorder="0"
                        // scrolling="false"
                        allowFullScreen={true}
                      // scrolling={'no'}
                      />
                    </Spin>
                  )}
                </DrawerForm>
              </>
            )}
            <Divider
              style={{
                marginBottom: -10,
              }}
            />
            {record && record.completeType === 3 && (
              <ListReceipt
                recordId={record?.id}
                type={2}
                reload={reload}
                deadlineTime={record?.deadlineTime}
              />
            )}
          </>
        </WaterMark>
      </Spin>
    </DrawerForm>
  );
};

export default DetailsRecord;
